<?php

/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2017/1/13
 * Time: 11:23
 */
class messageLiveModel
{
    const liveMsgListSchemeHead = 'joggers://liveMsgList/';
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->redis = &$this->base->redis;
        $this->descType = array(
            "L1"=>"%s ，您好！您参与的微课即将开始-%s",
            "L2"=>"%s ，您好！您参与的 %s \n 提问的问题：%s"
        );
    }

    /**
     * 推送消息
     * @param $id
     * @param string $fields
     * @return mixed
     */
    public function getMsgInfo($id, $fields='*') {
        return  $this->base->db->getRow("select $fields from r_live_message where id=$id");
    }

    /**
     * 发送消息
     * 观众端消息通知类型： 即将开始+回应
     * 主播端消息通知类型： 回应
     */
    public function sendMsg(array $params) {
        $mid = $params['mid'];//推送消息列表ID，非聊天室消息表的ID
        $toUid = $params['toUid'];
        $descType = $params['descType'];
        $sourceId = $params['sourceId'];//微课ID

        $pushContentDesc = $this->getPushContent(array(
            'descType'=>$descType,
            'uid'=>$toUid,
            'sourceId'=>$sourceId,
            'mid'=>$mid
        ));

        //发消息
        $extra = base64_encode(json_encode(array(
            "is_jogger"=>1,
            "id" => $mid,
            "user_id" => $sourceId,
            "user_name" => '微课live',
            "user_header" => $this->base->config['host'].'/static/images/share/pao.png',
            "content" => $pushContentDesc,
            "target_url"=>self::liveMsgListSchemeHead
        )));
        return $this->sendLiveMsg(array('target_id'=>$toUid,'extra'=>$extra,'content'=>''));
    }

    /**发消息
     * @param $data
     */
    public function sendLiveMsg($data) {
        $fromUserId = "14413";//test
        //$fromUserId = "12481157";//线上账号
        $toUserId = array($data['target_id']);
        $objectName = "RC:TxtMsg";
        $content = '{"content":"'.$data['content'].'","extra":"'.$data['extra'].'"}';
        $pushContent = "";
        $pushData = "1";
        return $this->base->load('message')->messagePublish($fromUserId,$toUserId ,$objectName,$content,$pushContent,$pushData);
    }

    /**
     * 内容渲染
     */
    public function getPushContent(array $params) {
        $descType = $params['descType'];
        $uid = $params['uid'];
        $sourceId = $params['sourceId'];
        $mid = $params['mid'];
        $pushContentDesc ='';
        /*内容渲染*/
        $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid,'nickname');
        $arrLiveInfo = $this->base->load('live/live')->getLiveInfo($sourceId, 'title');
        $title = $arrLiveInfo ? $arrLiveInfo['title'] : '';
        switch($descType) {
            case 'L1':
                $pushContentDesc = vsprintf($this->descType[$descType],array($nickname, $title));
                break;
            case 'L2':
                $msgInfo = $this->getMsgInfo($mid, 'mid');
                if ($msgInfo) {
                    $quesContent = '';
                    $chatroomMsgId = $msgInfo['mid'];
                    $parentId = $this->base->db->getOne("select parent_id from r_live_chatroom_message where id=$chatroomMsgId");
                    if ($parentId) {
                        $quesContent = $this->base->db->getOne("select content from r_live_chatroom_message_ext where mid=$parentId");
                    }
                    $pushContentDesc = vsprintf($this->descType[$descType],array($nickname, $title, $quesContent));
                }
                break;
        }
        return $pushContentDesc;
    }

    /**
     * 写入消息
     */
    public function addLiveMsg(array $params) {
        $data['live_id'] = $params['sourceId'];
        $data['desc_type'] = $params['descType'];
        $data['to_uid'] = $params['toUid'];
        $data['mid'] = $params['mid'];

        $data['create_time'] = time();
        $result = $this->base->db->insertRow('r_live_message',$data,mysqldb::INSERT_COMMON);
        return $result;
    }

    /**
     * 消息列表
     */
    public function getMsgList(array $params) {
        $uid = $params['uid'];
        $mid = $params['mid'];
        $offset = $params['offset'];
        $this->total = $this->base->db->getOne("select count(1) from r_live_message where to_uid=$uid");
        $list = [];
        if ($this->total > 0) {
            $where = "to_uid=$uid";
            if ($mid > 0) {
                $where .=" and id<$mid";
            }
            $list = $this->base->db->getAll("select * from r_live_message where $where  order by id desc limit $offset");
            //更新为已读
            $this->setMsgIsRead($uid);
        }
        return $list;
    }

    /**
     * 更新消息已读
     */
    public function setMsgIsRead($uid) {
        return $this->base->db->update("update r_live_message set is_read= 1 where to_uid=$uid");
    }

}